package com.dokimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.dokimall.common.utils.HttpUtils;
import com.dokimall.member.entity.MemberLevelEntity;
import com.dokimall.member.exception.PhoneExistException;
import com.dokimall.member.exception.UserNameExistException;
import com.dokimall.member.service.MemberLevelService;
import com.dokimall.member.vo.GiteeUserInfo;
import com.dokimall.member.vo.LoginUserVo;
import com.dokimall.member.vo.RegistVo;
import com.dokimall.member.vo.SociaUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dokimall.common.utils.PageUtils;
import com.dokimall.common.utils.Query;

import com.dokimall.member.dao.MemberDao;
import com.dokimall.member.entity.MemberEntity;
import com.dokimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(RegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        // 检查用户名是否重复
        memberEntity.setUsername(registVo.getUserName());
        checkUserNameUnique(registVo.getUserName());

        // 检查手机号是否已经注册
        memberEntity.setMobile(registVo.getPhoneNum());
        checkPhoneUnique(registVo.getPhoneNum());

        // 密码要进行加密保存，用Spring家的BCrytPasswordEncoder
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(registVo.getPassword());
        memberEntity.setPassword(encode);

        // 其他的默认信息（大部分等用户注册成功后自行添加）
        MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLev();
        memberEntity.setLevelId(memberLevelEntity.getId());
        memberEntity.setCreateTime(new Date());
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count>0){
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(LoginUserVo loginUserVo) {
        String accout = loginUserVo.getAccout();
        String password = loginUserVo.getPassword();
        // 校验账号是否存在（用户名、手机号、【邮箱后续添加】）
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", accout).or().eq("mobile", accout));
        if(entity!=null){
            // 校验密码 ，用Spring家的BCrytPasswordEncoder进行校验
            String passwordDB = entity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password,passwordDB);//校验的密码在前，加密的密码在后
            if (matches){
                return entity;
            }else{
                return null;
            }
        }else {
            return null;
        }
    }

    @Override
    public MemberEntity login(SociaUser sociaUser) throws Exception {
        String access_token = sociaUser.getAccess_token();
        // 认证成功,获取用户信息，uid
        Map<String,String> uidMap = new HashMap<>();
        uidMap.put("access_token",access_token);
        HttpResponse get = HttpUtils.doGet("https://gitee.com/", "api/v5/user", "get", new HashMap<>(), uidMap);
        if(get.getStatusLine().getStatusCode()==200){
            String string1 = EntityUtils.toString(get.getEntity());
            GiteeUserInfo giteeUserInfo = JSON.parseObject(string1, GiteeUserInfo.class);
            // 根据uid查询用户有没有注册过，如没有则自动注册
            int uid = giteeUserInfo.getId();
            MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid_gitee", uid));
            if(memberEntity!=null){
                // 已经注册过，更新令牌信息并返回用户数据
                MemberEntity update = new MemberEntity();
                update.setSocialUidGitee(String.valueOf(uid));
                update.setAccessToken(access_token);
                update.setExpiresIn(sociaUser.getExpires_in());
                this.baseMapper.updateById(update);
                memberEntity.setAccessToken(access_token);
                memberEntity.setExpiresIn(sociaUser.getExpires_in());
                return memberEntity;
            }else {
                // 没有注册过，用户登记到数据库中
                MemberEntity newSociaMem = new MemberEntity();
                // gitee用户名
                newSociaMem.setNickname(giteeUserInfo.getName());
                // git Uid、令牌以及过期时间
                newSociaMem.setSocialUidGitee(String.valueOf(uid));
                newSociaMem.setAccessToken(access_token);
                newSociaMem.setExpiresIn(sociaUser.getExpires_in());
                this.baseMapper.insert(newSociaMem);
                return newSociaMem;
            }
        }else {
            return null;
        }

    }

}